package com.ews.onlineexchange.controller;

import java.util.List;

import javax.enterprise.inject.Model;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.ChooseType;
import com.ews.onlineexchange.model.ServiceBuyer;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.service.EntityQuery;

@Model
public class OveredPriceComparisonBulletinList extends EntityQuery<Bulletin> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected List<Predicate> getRestrictions( CriteriaBuilder cb, Root<Bulletin> entity ) {
	
		List<Predicate> restrictions = super.getRestrictions( cb, entity );
		
		restrictions.add( cb.isTrue( entity.<Boolean>get( "over" ) ) );
		
		restrictions.add( cb.or( 
				cb.equal( entity.get( "wayOfChoose" ), ChooseType.Average ),
				cb.equal( entity.get( "wayOfChoose" ), ChooseType.Price )
		) );
		Join<Bulletin, ServiceBuyer> buyer = entity.join("buyer");
		//根据县区过滤
		super.addBulletinRegionRestriction_view(restrictions,buyer,cb);
		if(StringUtils.isNotBlank(getRegion())){
			restrictions.add(cb.equal(buyer.get("region"), getRegion()));
		}
		String projectName = (String)getParameterValues().get("projectName");
		if(StringUtils.isNotBlank(projectName)) {
			restrictions.add( cb.like( entity.<String>get( "projectName" ), getStringRestriction(projectName)) );
		}
		String supplierName = (String)getParameterValues().get("supplierName");
		if(StringUtils.isNotBlank(supplierName)) {
			Join<Bulletin, ServiceSupplier> supplier = entity.join("successTrade").join("supplier");
			restrictions.add( cb.like( supplier.<String>get( "cnname" ), getStringRestriction(supplierName)) );
		}
		String buyerName = (String)getParameterValues().get("buyerName");
		if(StringUtils.isNotBlank(buyerName)) {
			restrictions.add( cb.like( buyer.<String>get( "cnname" ), getStringRestriction(buyerName)) );
		}
		return restrictions;
		
	}

}
